using System;
using System.ComponentModel.Design;
using System.Linq;

namespace Microsoft.WowAddonStudio.FrameXml.Components.Designers
{
	/// <summary>
	/// Provides the base class for types that define a list of items used to create a smart tag panel.
	/// </summary>
	public class FrameXmlDesignerActionList : DesignerActionList
	{
		private readonly DesignerActionUIService designerActionUIService;

		/// <summary>
		/// Initializes a new instance of the <see cref="FrameXmlDesignerActionList"/> class.
		/// </summary>
		/// <param name="component">A component related to the <see cref="T:System.ComponentModel.Design.DesignerActionList"/>.</param>
		public FrameXmlDesignerActionList(IFrameXmlControl component) : base(component)
		{
			if (component == null)
				throw new ArgumentNullException("component");

			// Get the Designer Action UI service
			designerActionUIService = (DesignerActionUIService) GetService(typeof (DesignerActionUIService));
		}

        /// <summary>
        /// Gets the FrameXML control.
        /// </summary>
	    public IFrameXmlControl FrameXmlControl
	    {
            get { return this.Component as IFrameXmlControl; }
	    }

		/// <summary>
		/// Returns the collection of <see cref="T:System.ComponentModel.Design.DesignerActionItem"/> objects contained in the list.
		/// </summary>
		/// <returns>
		/// A <see cref="T:System.ComponentModel.Design.DesignerActionItem"/> array that contains the items in this list.
		/// </returns>
		public override DesignerActionItemCollection GetSortedActionItems()
		{
            var actionItems = new DesignerActionItemCollection();

            if (FrameXmlControl.HasActions)
			{
                var actions = FrameXmlControl.GetActions();

                foreach (var action in actions.Where(a => a.IsAvailable))
                {
                    var actionItem = new FrameXmlDesignerActionItem(this, action, true);

                    actionItem.Invoked += OnActionItemInvoked;
                    actionItems.Add(actionItem);
                }
			}

			return actionItems;
		}

        private void OnActionItemInvoked(object sender, EventArgs e)
        {
            // Refresh the Designer Action UI
            if (designerActionUIService != null)
                designerActionUIService.Refresh(Component);
        }
 	}
}